#include <flgrCoreData.h>
#include <flgrCoreThreads.h>
#include <flgrCoreThreadsAuto.h>
#include <flgrCoreMalloc.h>
#include <flgrImageIO.h>
#include <flgrMorphoBase.h>

#include <time.h>

/*! 
 * \example multithread_auto.c <B>Automatic thread creation for some specific functions</B>
 */



#define BENCH_FUCTION(nbtime,textinfo,function,...)			\
  {									\
    time_t before_t, after_t;						\
    clock_t before_c, after_c;						\
    int i;								\
									\
    before_t = time(NULL);						\
    before_c = clock();							\
									\
    for(i=0;i<nbtime;i++) {						\
      function(__VA_ARGS__);						\
    }									\
    									\
    after_t = time(NULL);						\
    after_c = clock();							\
									\
    printf(textinfo " System time : %d us, CPU time : %d us \n",	\
	   (int) (((after_t-before_t)*1000000)/nbtime),			\
	   (int) ((after_c-before_c)/(CLOCKS_PER_SEC/1000000)/nbtime)); \
  }






int main(int argc, char *argv[]) {
  FLGR_Data2D *imin;
  FLGR_Data2D *imDest1;
  FLGR_Data2D *imDest2;
  FLGR_Data2D *nhb;
  int nb_threads;

  if(argc <= 1) {
    POST_ERROR("Command line : %s <nb_thread> \n",argv[0]);
    return 1;
  }

  sscanf(argv[1],"%d",&nb_threads);

  imin    = flgr2d_load_pgm("../../images/gray/cameraman.pgm");
  imDest1 = flgr2d_create_pixmap_from(imin);
  imDest2 = flgr2d_create_pixmap_from(imin);
  nhb     = flgr2d_create_neighborhood(3,3,1,FLGR_UINT8,FLGR_RECT,FLGR_8_CONNEX);
  
  //flgr2d_median(imDest1, imin, nhb);
  BENCH_FUCTION(10000,"Median",
		flgr2d_median,imDest1, imin, nhb);


  //flgr2d_thread_function_data2d_data2d_nhb(flgr2d_median,imDest2,imin,nhb,4);
  BENCH_FUCTION(10000,"Auto Multi-thread Median",
		flgr2d_thread_function_data2d_data2d_nhb,
		flgr2d_median,imDest2,imin,nhb,nb_threads);

  flgr2d_save_pgm(imDest1,"median",5);
  flgr2d_save_pgm(imDest2,"median_multithreaded_auto",5);

  flgr2d_destroy(imin);
  flgr2d_destroy(imDest1);
  flgr2d_destroy(imDest2);
  flgr2d_destroy(nhb);

  return 0;
}


